package io.renren.modules.sys.controller;

import io.renren.common.exception.RRException;
import io.renren.common.utils.FileUtils;
import io.renren.common.utils.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

/**
 * @author wangyi
 * @mail 794651397@qq.com
 * @createdate 2018/2/24 13:31
 **/
@RestController
@RequestMapping("/sys/file")
public class FileController {
    @Value("${uploadImgPath}")
    private String uploadImgPath;//图片上传路径

    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    public R uploadFile(@RequestParam MultipartFile file) {
        // 取文件名
        String fileName = file.getOriginalFilename();
        // 取文件后缀
        String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
        String path= System.currentTimeMillis() +"."+ fileType;
        String filePath = uploadImgPath + path;
        try {
            file.transferTo(new File(filePath));
        }catch (Exception e) {
            e.printStackTrace();
            throw new RRException("图片上传失败");
        }
        return R.ok().put("path", path).put("fileName",fileName);
    }

    @RequestMapping(value = "/getImg", method = RequestMethod.GET)
    public R getImg(@RequestParam String path, HttpServletResponse response) throws Exception {
        FileUtils.getImg(uploadImgPath + path, response);
        return R.ok();
    }

    @RequestMapping(value = "/downloadFile", method = RequestMethod.GET)
    public R downloadFile(@RequestParam String path, HttpServletResponse response) throws Exception {
//        req.setCharacterEncoding("UTF-8");
//        //第一步：设置响应类型
//        resp.setContentType("application/force-download");//应用程序强制下载
        //第二读取文件
        String filepath =uploadImgPath+path;
        InputStream in = new FileInputStream(filepath);
        //设置响应头，对文件进行url编码
        path = URLEncoder.encode(path, "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename="+path);
        response.setContentLength(in.available());

        //第三步：老套路，开始copy
        OutputStream out = response.getOutputStream();
        byte[] b = new byte[1024];
        int len = 0;
        while((len = in.read(b))!=-1){
            out.write(b, 0, len);
        }
        out.flush();
        out.close();
        in.close();
        return R.ok();
    }

}
